package com.gxa.customer.service.Impl;


import com.gxa.common.pojo.SysMenu;
import com.gxa.common.pojo.SysRole;
import com.gxa.common.pojo.SysUser;
import com.gxa.customer.security.common.SecurityUser;
import com.gxa.customer.service.PermissionService;
import com.gxa.customer.service.RoleService;
import com.gxa.customer.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询数据
        SysUser user = userService.selectByUsername(username);
        //判断
        if(user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //根据用户id查询所有的角色
        List<SysRole> sysRoles = roleService.selectRolesByUserId(user.getId());
        List<String> permissionValueList=new ArrayList<>();

        for (SysRole sysRole : sysRoles) {
            //根据用户角色查询用户权限列表
            permissionValueList.add(sysRole.getName());
            List<SysMenu> sysMenus = permissionService.selectAllMenuByRoleId(sysRole.getId());
            for (SysMenu sysMenu : sysMenus) {
                permissionValueList.add(sysMenu.getPerms());
            }
        }
        SecurityUser securityUser = new SecurityUser();
        //塞对象
        securityUser.setCurrentUserInfo(user);
        //塞权限
        securityUser.setPermissionValueList(permissionValueList);
        return securityUser;
    }
}
